package com.qingke.example;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.qingke.dao.ChatDao;
import com.qingke.pojo.Message;
import com.qingke.pojo.User;


/**
 * Servlet implementation class SendMessageServlet
 */
@WebServlet("/SendMessageServlet")
public class SendMessageServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

       
    public SendMessageServlet() {
        super();
    }
    



	@SuppressWarnings("unchecked")
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");
		List<String> msgs=(List<String>)request.getServletContext().getAttribute("chat");
		if(msgs==null){
			msgs=new ArrayList<String>();
		}
		String username=(String)request.getSession().getAttribute("username");
		User user =new User();
		ChatDao cd =new ChatDao();
		user=cd.login(username);
		String name=user.getName();
		Date date= new Date();
		
		String msg=request.getParameter("message");
		Message meg=new Message();
		meg.setName(name);
		meg.setMessage(msg);
		meg.setTime(new java.sql.Timestamp(date.getTime()));
		cd.insert(meg);
		System.out.println("send success");
		SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
		
		String message=name+":"+msg+" "+sdf.format(date);
		if(message!=null&&!message.trim().equals("")){
			msgs.add(message);
		}
		request.getServletContext().setAttribute("chat", msgs);
		response.getWriter().append("success");
		
		cd.close();
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}
	
	
	
}
